package fr.ginvest.implementation;

import java.util.Collection;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import fr.ginvest.entity.Startup;
import fr.ginvest.interfaces.StartupFacadeRemote;

/**
 * Session Bean implementation class StartupFacade
 */
@Stateless

public class StartupFacade implements StartupFacadeRemote {

	@PersistenceContext
	protected EntityManager entityMgr;
	public StartupFacade() {
	}	

	public StartupFacade(EntityManager entityMgr) {
		this.entityMgr = entityMgr;
	}
	
    public Startup findStartupById(int id) {
        return entityMgr.find(Startup.class, id);
    }
    
    public void deleteStartup(Startup s) {
    	entityMgr.remove(s);
    }
    
    public Startup updateStartup(Startup s) {
    	return entityMgr.merge(s);
    }
    
    public Startup addStartup(Startup s) {
    	entityMgr.persist(s);
		return s;
    }

	@SuppressWarnings("unchecked")
	@Override
	public Collection<Startup> listStartups() {
		return entityMgr.createQuery("SELECT s FROM Startup AS s").getResultList();
	}

	@Override
	public Startup findStartupByName(String name) {
		final String queryString = "select s from Startup as s where s.nom=:name";
		Query query = entityMgr.createQuery(queryString);
		query.setParameter("name", name);
		if(query.getResultList().size() == 0)
			return null;
		else
			return (Startup) query.getSingleResult();
	}

	@SuppressWarnings("unchecked")
	@Override
	public Collection<Startup> listActiveStartups() {
		final String queryString = "select s from Startup as s where s.etat=:etat";
		Query query = entityMgr.createQuery(queryString);
		query.setParameter("etat", Startup.Etat.ACTIF);
		return query.getResultList();
	}

	@Override
	public Startup authenticate(String login, String password) {
		if (login == null || "".equals(login))
            return null;

		Startup startup = this.findStartupByLogin(login);

        // Check if it's the right password
        if (startup != null){
        	if(startup.matchPassword(password)){
        		return startup;
        	} 
        }
        return null;
	}

	@Override
	public Startup findStartupByLogin(String login) {
		final String queryString = "select s from Startup s where s.login= :login";
		Query query = entityMgr.createQuery(queryString).setParameter("login", login);
		if(query.getResultList().size() == 0)
			return null;
		else
			return (Startup) query.getSingleResult();
	}
}
